package com.cncf.interceptor;

import com.cncf.entity.Enterprise;
import com.cncf.util.JedisUtil;
import com.cncf.util.ObjectAndByte;
import com.cncf.util.TokenConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import redis.clients.jedis.Jedis;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zj
 */
public class EnterpriseInnerAccessTokenValidationInterceptor extends HandlerInterceptorAdapter {

    private static Logger logger = LoggerFactory.getLogger(EnterpriseInnerAccessTokenValidationInterceptor.class);

    //白名单 TODO 改为配置 通用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        logger.info("************:" + request.getRequestURI());
        this.checkLogin(request, response, handler);
        return super.preHandle(request, response, handler);
    }

    private boolean checkLogin(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String AccessToken = request.getHeader(TokenConfig.ENTERPRISE_INNER_AUTHORIZATION);
        Jedis jedis = JedisUtil.getJedis();
        try {
            byte[] bytes = jedis.get(AccessToken.getBytes());
            if (bytes == null) {
                response.setStatus(401);
                throw new LoginException("登录失效");
            } else {
                Enterprise enterprise = (Enterprise) ObjectAndByte.toObject(bytes);
                if (enterprise == null) {
                    response.setStatus(401);
                    throw new LoginException("登录失效");
                } else {
                    enterprise.setAccesstoken(AccessToken);
                    request.setAttribute(TokenConfig.DEFAULT_USERID_REQUEST_ATTRIBUTE_NAME, enterprise);
                    //将这句迁移到了登录方法里，相当于网站的30天内自动登录。
                    //jedis.expire(AccessToken.getBytes(), 60 * 60 * 24 * 30);//缓存用户信息30天
                }
            }
        } catch (Exception e) {
            response.setStatus(401);
            throw new LoginException("登录失效");
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }

        return true;
    }
}
